package com.cjx.stars.utils;


import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.cjx.stars.common.MyException;
import com.cjx.stars.properties.SMSProperties;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;


import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import static com.cjx.stars.constant.FailMessage.THE_SMS_MESSAGE_IS_SENT_ABNORMALLY;


/**
 * @author cjx
 */
@Log4j2
@Component
public class AliyunSmsSenderUtil {

    private static SMSProperties smsProperties;

    @Resource
    private SMSProperties tempProperties;





    /**
     * 使用AK&SK初始化账号Client
     * @return Client
     */
    public static com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(smsProperties.getAccessKey())
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(smsProperties.getSecretKey());
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = smsProperties.getEndpoint();
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 发送验证码给目标手机号
     * @param phoneNumber 手机号
     * @param code 验证码
     */
    public static void sendMessage(String phoneNumber , String code)  {
        com.aliyun.dysmsapi20170525.Client client;
        try {
            client = AliyunSmsSenderUtil.createClient();
        } catch (Exception e) {
            throw new MyException(THE_SMS_MESSAGE_IS_SENT_ABNORMALLY);
        }

        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName(smsProperties.getSignName())
                .setTemplateCode(smsProperties.getTemplateCode())
                .setPhoneNumbers(phoneNumber)
                .setTemplateParam("{\""+smsProperties.getTemplateParam()+"\":\""+code+"\"}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (Exception error) {
            throw new MyException(THE_SMS_MESSAGE_IS_SENT_ABNORMALLY);
        }

    }

    @PostConstruct
    public void initProperties() {
        smsProperties = tempProperties;
    }
}